package com.android.waterdetection.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.android.waterdetection.MainActivity;
import com.android.waterdetection.R;
import com.android.waterdetection.dao.DBService;
import com.android.waterdetection.utils.ToastUtil;

import java.lang.ref.WeakReference;

import static android.content.Context.MODE_PRIVATE;

public class AccountFragment extends Fragment {

    private static final String TAG = "AccountFragment";

    private TextView mTvAccount;
    private RelativeLayout mRaChangePass;
    private RelativeLayout mRaLogout;
    private RelativeLayout mRaQuit;
    private ProgressBar mProgressBar;

    private Handler mHandler;
    private String mLoginName;
    private String mPassword;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_account, container, false);
        initView(root);
        initData();
        initListener();
        return root;
    }

    private void initListener() {
        mRaChangePass.setOnClickListener(view -> {
            View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.item_dialog_chage_password, null, false);
            EditText edtOldPass = dialogView.findViewById(R.id.edt_old_pass);
            EditText edtPass = dialogView.findViewById(R.id.edt_pass);
            EditText edtSurePass = dialogView.findViewById(R.id.edt_sure_pass);
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle(requireContext().getString(R.string.change_password));
            dialog.setView(dialogView);
            dialog.setPositiveButton(requireContext().getString(R.string.sure), (dialog1, which) -> {
                String oldPass = edtOldPass.getText().toString().trim();
                String pass = edtPass.getText().toString().trim();
                String surePass = edtSurePass.getText().toString().trim();
                if (!oldPass.equals(mPassword)) {
                    ToastUtil.showToast(requireContext(), getString(R.string.old_pass_fail));
                } else if (!pass.equals(surePass)) {
                    ToastUtil.showToast(requireContext(), getString(R.string.pass_edt_two_fail));
                } else if (pass.isEmpty() || surePass.isEmpty()) {
                    ToastUtil.showToast(requireContext(), getString(R.string.pass_not_null));
                } else {
                    mProgressBar.setVisibility(View.VISIBLE);
                    new Thread(() -> {
                        boolean userPassword = DBService.updateUserPassword(mLoginName, surePass);
                        Message message = new Message();
                        message.what = 2;
                        message.obj = userPassword;
                        mHandler.sendMessage(message);
                    }).start();
                    dialog1.dismiss();
                }
            });
            dialog.setNegativeButton(requireContext().getString(R.string.cancel), null);
            dialog.create().show();
        });
        mRaLogout.setOnClickListener(view -> {
            View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.item_dialog_logout, null, false);
            EditText edtPassword = dialogView.findViewById(R.id.edt_logout_pass);

            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle(requireContext().getString(R.string.hint));
            dialog.setMessage(requireContext().getString(R.string.sure_logout));
            dialog.setView(dialogView);
            dialog.setPositiveButton(requireContext().getString(R.string.sure), (dialog1, which) -> {
                String pass = edtPassword.getText().toString().trim();
                if (!pass.equals(mPassword)) {
                    ToastUtil.showToast(requireContext(), getString(R.string.old_pass_fail));
                    return;
                }
                mProgressBar.setVisibility(View.VISIBLE);
                new Thread(() -> {
                    boolean deleteUser = DBService.deleteUser(mLoginName);
                    Message message = new Message();
                    message.what = 1;
                    message.obj = deleteUser;
                    mHandler.sendMessage(message);
                }).start();
                dialog1.dismiss();
            });
            dialog.setNegativeButton(requireContext().getString(R.string.cancel), null);
            dialog.create().show();
        });
        mRaQuit.setOnClickListener(v -> {
            SharedPreferences autoLogin = getActivity().getSharedPreferences("autoLogin", MODE_PRIVATE);
            SharedPreferences loginName = getActivity().getSharedPreferences("loginName", MODE_PRIVATE);
            SharedPreferences.Editor autoEdit = autoLogin.edit();
            SharedPreferences.Editor loginEdit = loginName.edit();
            autoEdit.putBoolean("autoLogin", false);
            loginEdit.putString("loginName", null);
            autoEdit.apply();
            loginEdit.apply();
            Intent intent = new Intent(getActivity(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        });
    }

    private void initData() {
        mLoginName = getActivity().getIntent().getExtras().getString("loginName");
        mPassword = getActivity().getIntent().getExtras().getString("password");
        mTvAccount.setText(mLoginName);

        mHandler = new AccountStaticHandler(this);

    }

    private void initView(View root) {
        mTvAccount = root.findViewById(R.id.tv_account);
        mRaChangePass = root.findViewById(R.id.rat_changePass);
        mRaLogout = root.findViewById(R.id.rat_logout);
        mRaQuit = root.findViewById(R.id.rat_quit);
        mProgressBar = root.findViewById(R.id.pro_loading);
    }

    private static final class AccountStaticHandler extends Handler {
        private final WeakReference<AccountFragment> mFragmentWeakReference;

        public AccountStaticHandler(AccountFragment fragment) {
            mFragmentWeakReference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            AccountFragment accountFragment = mFragmentWeakReference.get();

            switch (msg.what) {
                case 1:
                    accountFragment.mProgressBar.setVisibility(View.GONE);

                    boolean isDelete = (boolean) msg.obj;
                    if (isDelete) {
                        ToastUtil.showToast(accountFragment.requireContext(), accountFragment.getString(R.string.logout_zx_cg));
                        Intent intent = new Intent(accountFragment.getActivity(), MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        accountFragment.startActivity(intent);
                    } else {
                        ToastUtil.showToast(accountFragment.requireContext(), accountFragment.getString(R.string.logout_zx_fail));
                    }
                    break;

                case 2:
                    accountFragment.mProgressBar.setVisibility(View.GONE);

                    boolean isUpdate = (boolean) msg.obj;
                    if (isUpdate) {
                        ToastUtil.showToast(accountFragment.requireContext(), accountFragment.getString(R.string.change_success));
                        Intent intent = new Intent(accountFragment.getActivity(), MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        accountFragment.startActivity(intent);
                    } else {
                        ToastUtil.showToast(accountFragment.requireContext(), accountFragment.getString(R.string.change_fail));
                    }
                    break;
            }
        }
    }
}